<template>
  <div>
    <main-nav index="5"></main-nav>
    <i-spin size="large" fix v-if="!loaded"></i-spin>
    <div class="container margin-top-15">
      <i-row :gutter="15" type="flex">
        <i-col :span="18">
          <video-player class="video-player-box"
            ref="videoPlayer"
            :options="playerOptions"
            :playsinline="true"
            v-if="loaded"
            @ready="playerReady">
          </video-player>
        </i-col>
        <i-col :span="6">
          <i-card dis-hover :bordered="true" class="chatbox-records">
            <p slot="title">
              <span>聊天室</span>
              <small v-if="total">共 {{total}} 人在线</small>
            </p>
            <div class="records" id="records" @scroll="scrolling = true">
              <ul>
                <li v-for="(item, index) in messages" :key="'message_' + index" :class="{system: !item.createdBy}">
                  <span class="owner" v-if="item.createdBy">{{item.createdBy.name}}:</span>
                  <span>{{item.text}}</span>
                </li>
              </ul>
            </div>
          </i-card>
          <i-input placeholder="一起互动" class="chatbox-input" v-model="input" @on-enter="send" :disabled="!online">
            <i-button slot="append" @click="send">发送</i-button>
          </i-input>
        </i-col>
      </i-row>
    </div>
  </div>
</template>

<script>
import MainNav from '../components/main-nav'
import 'video.js/dist/video-js.css'
import { videoPlayer } from 'vue-video-player'
// videojs
import videojs from 'video.js'
import { mapActions } from 'vuex'

window.videojs = videojs
require('videojs-contrib-hls/dist/videojs-contrib-hls.js')

export default {
  data() {
    return {
      loaded: false,
      height: 200,
      title: '',
      source: null,
      avatar: null,
      socket: null,
      id: null,
      total: 0,
      input: null,
      messages: [],
      online: false,
      scrolling: false
    }
  },
  components: {
    MainNav,
    videoPlayer
  },
  methods: {
    ...mapActions({
      getLive: 'getLive'
    }),
    playerReady(player) {
      const containerStyle = player.el_.style
      const style = player.tech_.el_.style
      containerStyle.maxHeight = style.maxHeight = '480px'
      containerStyle.minHeight = style.minHeight = '280px'
      containerStyle.height = style.height = 'auto'
      containerStyle.width = style.width = '100%'
      style.position = 'relative'
      // var hls = player.tech({ IWillNotUseThisInPlugins: true }).hls
      player.tech_.hls.xhr.beforeRequest = function(options) {
        // console.log(options)
        return options
      }
      // console.log(hls)
    },
    send() {
      if (!this.input) return
      var msg = JSON.stringify({
        value: this.input,
        type: 0
      })
      this.socket.send(msg)
      this.input = null
    },
    connect() {
      this.socket = new WebSocket(
        'ws://' +
          location.hostname +
          ':9000' +
          '/api/chatting/connect/' +
          this.id +
          '?ticket=' +
          localStorage.ticket
      )
      const that = this
      function updateScroll() {
        setTimeout(() => {
          var element = document.getElementById('records')
          element.scrollTop = element.scrollHeight
        }, 500)
      }

      this.socket.onmessage = msg => {
        const message = JSON.parse(msg.data)
        let text = null
        if (message.success) {
          let createdBy = null
          switch (message.type) {
            case 0:
              text = message.value
              createdBy = message.createdBy
              break
            case 99:
              text = '欢迎 ' + message.createdBy.name + ' 进入聊天室'
              that.total = Number.parseInt(message.value)
              break
            case 100:
              text = message.createdBy.name + ' 离开了'
              that.total = Number.parseInt(message.value)
              break
          }
          that.messages.push({
            text: text,
            createdBy: createdBy
          })
          updateScroll()
        } else {
          this.$Message.error(message.value)
        }
      }
      this.socket.onopen = () => {
        that.online = true
        that.messages = []
      }
      this.socket.onclose = () => {
        that.online = false
      }
    }
  },
  computed: {
    playerOptions() {
      return {
        sources: [
          {
            withCredentials: false,
            type: 'application/x-mpegURL',
            // src: "http://ivi.bupt.edu.cn/hls/chchd.m3u8"
            src: this.source
          }
        ],
        controlBar: {
          timeDivider: false,
          durationDisplay: false
        },
        flash: { hls: { withCredentials: false } },
        html5: { hls: { withCredentials: false } },
        poster:
          this.avatar ||
          'https://surmon-china.github.io/vue-quill-editor/static/images/surmon-5.jpg'
      }
    }
  },
  mounted() {
    this.height = document.body.clientHeight - 120
    const that = this
    this.id = this.$route.params.id
    this.getLive({
      id: this.id,
      callback(data) {
        if (!data) return
        that.source = data.source
        that.avatar = data.avatar
        that.title = data.title
        that.loaded = true
        that.connect()
      }
    })
  }
}
</script>

<style lang="less" scoped>
.chatbox-records {
  top: 0;
  position: absolute;
  bottom: 40px;
  left: 0;
  right: 0;
  .records {
    overflow: auto;
    position: absolute;
    bottom: 5px;
    top: 55px;
    left: 10px;
    right: 10px;
    font-size: 12px;
    li {
      margin-top: 2px;
      &.system {
        color: #666;
        font-size: 11px;
        text-align: center;
      }
    }
  }
}
.chatbox-input {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  top: inherit;
}
</style>
